package com.ruoyi.auth.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.model.LoginParamModel;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.auth.utils.OkHttpUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginResultModel;
import com.ruoyi.system.api.model.LoginUser;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.tiankafei.common.model.ApiResult;
import org.tiankafei.common.utils.JacksonUtil;

/**
 * token 控制
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    public static final String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH\n" +
            "nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==";

    public static final String PRI_KEY = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY\n" +
            "7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKN\n" +
            "PuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gA\n" +
            "kM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWow\n" +
            "cSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99Ecv\n" +
            "DQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthh\n" +
            "YhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3\n" +
            "UP8iWi1Qw0Y=";

    private RSA rsa = SecureUtil.rsa(PRI_KEY, publicKey);

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        String password = null;
        try {
            // 解密
            password = rsa.decryptStr(form.getPassword(), KeyType.PrivateKey);
        } catch (Exception e) {
            throw new ServiceException("用户/密码错误，请检查！");
        }
        if (StringUtils.isEmpty(password)) {
            throw new ServiceException("用户/密码错误，请检查！");
        }
        LoginResultModel loginResultModel = null;
        if (!"admin".equals(form.getUsername()) && !"username".equals(form.getUsername()) && !"leader".equals(form.getUsername())) {
            // 登录接口
            String loginUrl = "http://10.10.60.231:9990/zzjg/user/login";
            LoginParamModel loginParamModel = new LoginParamModel();
            loginParamModel.setDlbm(form.getUsername());
            loginParamModel.setKl(password);
            try {
                ApiResult<LoginResultModel> loginResult = OkHttpUtils.postRequestBody(loginUrl, loginParamModel, new TypeReference<ApiResult<LoginResultModel>>() {
                });
                loginResultModel = loginResult.getData();
                if (loginResultModel == null) {
                    throw new ServiceException("用户/密码错误，请检查！");
                }
                log.info("当前登录用户：{}", JacksonUtil.toJSONString(loginResultModel));

                String mc = loginResultModel.getMc();
                Map<String, String> dataMap = getDataMap();
                if ("赵博文".equals(mc)) {
                    form.setUsername("admin");
                    password = "admin123";
                    loginResultModel.setYhlx("1");
                } else {
                    if (dataMap.get(mc).equals(mc)) {
                        // leader
                        form.setUsername("leader");
                        password = "admin123";
                        loginResultModel.setYhlx("2");
                    } else {
                        // 组员
                        form.setUsername("username");
                        password = "admin123";
                        loginResultModel.setYhlx("3");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new ServiceException("用户/密码错误，请检查！");
            }
        }

        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), password);
        userInfo.setLoginResultModel(loginResultModel);
        // 获取登录token
        Map<String, Object> token = tokenService.createToken(userInfo);
        return R.ok(token);
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    private Map<String, String> getDataMap() {
        Map<String, String> dataMap = Maps.newHashMap();

        dataMap.put("魏双双", "魏双双");
        dataMap.put("杨帆", "魏双双");
        dataMap.put("潘向雷", "魏双双");
        dataMap.put("马东运", "魏双双");
        dataMap.put("王君博", "魏双双");
        dataMap.put("王叶飞", "魏双双");
        dataMap.put("赵健", "魏双双");
        dataMap.put("张洋", "魏双双");

        dataMap.put("张江斌", "张江斌");
        dataMap.put("尚泽", "张江斌");

        dataMap.put("徐鹏飞", "徐鹏飞");
        dataMap.put("王丁丁", "徐鹏飞");
        dataMap.put("付海超", "徐鹏飞");

        dataMap.put("赵金兵", "赵金兵");
        dataMap.put("杨明明", "赵金兵");
        dataMap.put("凌守印", "赵金兵");
        dataMap.put("杨增林", "赵金兵");

        dataMap.put("杨代胜", "杨代胜");
        dataMap.put("刘强建", "杨代胜");
        dataMap.put("朱润东", "杨代胜");
        dataMap.put("郭志强", "杨代胜");
        dataMap.put("李宝灯", "杨代胜");

        dataMap.put("于涛", "于涛");
        dataMap.put("王楠", "于涛");
        dataMap.put("张少康", "于涛");
        dataMap.put("倪欣欣", "于涛");
        dataMap.put("卜凯", "于涛");
        dataMap.put("吕文启", "于涛");

//        dataMap.put("马杰", "马杰");
        dataMap.put("赵博文", "赵博文");

        return dataMap;
    }

}
